package com.andova.image

import android.graphics.*
import android.hardware.Camera
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException

/**
 * Bitmap转字符数组
 */
fun bitmapToBytes(bitmap: Bitmap?): ByteArray? {
    if (bitmap == null) return null
    val os = ByteArrayOutputStream()
    // scale
    val options = 100
    // Store the bitmap into output stream(no compress)
    bitmap.compress(Bitmap.CompressFormat.JPEG, options, os)
    try {
        return os.toByteArray()
    } catch (e: NullPointerException) {
        e.printStackTrace()
    } finally {
        try {
            os.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    return null
}

fun imageToBytes(file: File): ByteArray? {
    if (!file.exists()) return null
    return file.readBytes()
}

fun compressBase64(base64: String, maxKB: Int, flag: Int) = compressBase64(Base64.decode(base64, flag), maxKB)
fun compressBase64(base64: ByteArray, maxKB: Int): Bitmap? {
    val originalkb = base64.size / 1024f
    if (originalkb <= maxKB) return BitmapFactory.decodeByteArray(base64, 0, base64.size)
    val scale = originalkb / maxKB
    var samsize = -1
    for (i in 2..8) {
        if (i >= scale) {
            samsize = i
            break
        }
    }
    if (samsize == -1) return null
    val option = BitmapFactory.Options().apply { inJustDecodeBounds = true }
    BitmapFactory.decodeByteArray(base64, 0, base64.size, option)
    option.inSampleSize = samsize
    option.inJustDecodeBounds = false
    return BitmapFactory.decodeByteArray(base64, 0, base64.size, option)
}

fun decodeToOriginalBitmap(data: ByteArray?, camera: Camera?) {
    if (data == null || camera == null) return
    var bitmap: Bitmap? = null
    var stream: ByteArrayOutputStream? = null
    try {
        val size = camera.parameters.previewSize
        val imageW = size.width
        val imageH = size.height
        val image = YuvImage(data.clone(), ImageFormat.NV21, imageW, imageH, null)
        stream = ByteArrayOutputStream()
        image.compressToJpeg(Rect(0, 0, imageW, imageH), 100, stream)
        bitmap = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size())
    } catch (e: Exception) {
    } finally {
        try {
            stream?.close()
        } catch (ignored: IOException) {
        }
    }
    bitmap?.recycle()
}

fun decodeToOriginalBitmap(src: ByteArray, dst: File, imageWidth: Int, imageHeight: Int) {
    val fos = FileOutputStream(dst)
    try {
        val image = YuvImage(src, ImageFormat.NV21, imageWidth, imageHeight, null)
        image.compressToJpeg(Rect(0, 0, imageWidth, imageHeight), 100, fos)
    } catch (e: Exception) {
        e.printStackTrace()
    } finally {
        try {
            fos.close()
        } catch (ignored: IOException) {
        }
    }
}